<template>
  <div class="header">
    <div class="search-return" @click="goBack">
      <i class="iconfont icon-return"></i>
    </div>
    <div class="search-main">
      <i class="iconfont icon-iconfont-seach"></i>
      <!-- 在移动端input应该加一个form表单外壳 -->
      <form action="" onsubmit="return false" @keyup.enter="goSearchList">
        <input
          type="search"
          placeholder="搜索你喜欢的产品..."
          v-model="searchVal"
          autofocus
          ref="myInput"
        />
      </form>
    </div>
    <div class="search-btn" @click="goSearchList">搜索</div>
  </div>
</template>

<script>
export default {
  name: "Header",
  data() {
    return {
      searchVal: this.$route.query.key || "",
      searchArr: [],
    };
  },
  created() {},
  mounted() {
    //键盘监听事件
    window.addEventListener("touchmove", this.myTouchMove, true);
  },
  methods: {
    //失去焦点
    myTouchMove() {
      this.$refs.myInput.blur();
    },

    //
    goBack() {
      this.$router.back();
    },
    goSearchList() {
      //判断输入的值是否为空
      if (!this.searchVal) return;
      //判断之前有没有搜索的本地存储
      if (!localStorage.getItem("searchList")) {
        //没有，就设置
        localStorage.setItem("searchList", "[]");
      } else {
        //之前有，就获取
        this.searchArr = JSON.parse(localStorage.getItem("searchList"));
      }

      //增加数据
      this.searchArr.unshift(this.searchVal);
      //ES6去重
      let newArr = new Set(this.searchArr);
      //存放到本地存储
      localStorage.setItem("searchList", JSON.stringify(Array.from(newArr)));

      //当前跳转当前路由，则路由不跳转
      if (this.searchVal == this.$route.query.key) return;
      //页面跳转
      this.$router.push({
        name: "List",
        query: {
          //传值，为了给保持搜索框里跳时保留搜索值
          key: this.searchVal,
        },
      });
    },
  },
};
</script>

<style scoped lang="less">
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 1.2rem;
  background-color: #b0352f;
  color: #fff;

  .search-return {
    padding: 0 0.25rem;

    i {
      font-size: 0.75rem;
    }
  }

  .search-main {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 0.8rem;
    width: 7.2rem;
    border-radius: 0.75rem;
    background-color: #fff;

    form {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 80%;
      // color: #999

      input {
        font-size: 0.4rem;
        width: 100%;
        color: #000;
      }
    }
    i {
      color: #999;
      margin: 0 0.125rem 0 -0.5rem;
    }
  }

  .search-btn {
    padding: 0 0.25rem;
    font-size: 0.48rem;
  }
}
</style>
